<?php

class BCafeBillCooker extends BAWeBillCooker {

    public function getCookerViewPath($relativePath = TRUE) {
        return 'weBill';
    }

    public function onAddBill($data = NULL) {
        $mobile = '';
        $openid = '';
        $name = '';
        //parent::onAddBill($data);
        $billMedias = $this->postManager->populateMediaListFromPostData($this->postData, 'add_bill');
        //$memberMedias = $this->postManager->populateMediaListFromPostData($this->postData, 'member_info');
        $deductMedias = $this->postManager->populateMediaListFromPostData($this->postData, 'change_memberPoint');

        $billType = $this->getCurrentBillType();
        /*
          $bill = $this->getCurrentBill();
          if ($bill instanceof BTreeList) {
          if ($bill->getName() != 'list' . $bill->getId()) {
          $bill->name = 'list'.$bill->getId();
          $bill->setOwner($billType);
          $bill->save();
          }
          }
         * 
         */

        $billData = array();
        $memberData = array();

        $memberPointAccountId = $this->activeLink->getLinkVariable('memberPointAccountId');
        $mobile = $this->activeLink->getLinkVariable('mobile');
        if ($mobile != NULL) {
            $memberData['mobile'] = $mobile;
        }
        $openid = $this->activeLink->getLinkVariable('openid');
        if ($openid != NULL) {
            $memberData['openid'] = $openid;
        }
        $name = $this->activeLink->getLinkVariable('name');
        if ($name != NULL) {
            $memberData['name'] = $name;
        }
        $fixedCardId = $this->activeLink->getLinkVariable('fixedCardId');
        if ($fixedCardId != NULL) {
            $memberData['fixedCardId'] = $fixedCardId;
        }

        foreach ($billMedias as $media) {
            if ($media->content != NULL)
                $billData[$media->name] = $media->content;
        }
        $billData['billTime'] = time();

        if ($billType != NULL) {
            //get type attributes from type table, it is added in addType funtion
            $typeAttributeTable = new BAAttributeSheet($billType);
            $typeList = $typeAttributeTable->getList(array('itemData' => array('billTypeId' => $billType->getId())));

            $currency = $typeList->getItem('currency')->getValue();
            $currencyUnit = $typeList->getItem('currencyUnit')->getValue();
            $discountRate = $typeList->getItem('discountRate')->getValue();

            //then add memberPoint
            if ($memberPointAccountId != NULL && $memberPointAccountId > 0) {
                $memberPointCooker = new BAMemberPointCooker();
                $memberPointAccount = $memberPointCooker->getMemberPointAccount($memberPointAccountId);
                $money = $billData['amount'];

                if ($memberPointAccount != NULL) {
                    $memberData['memberPointAccountId'] = $memberPointAccount->getId();

                    $discountMoney = 0;
                    $addPoint = 0;
                    //$mpType = $memberPointCooker->getMemberPointTypeByAccount($memberPointAccount);
                    if (is_numeric($discountRate) && $discountRate > 0 && $discountRate < 100) {
                        $discountMoney = $money * $discountRate * 0.01;

                        $memberPointCooker->addMemberPointByMoney($discountMoney, $memberPointAccount, $currencyUnit, $currency);
                        $addPoint = $memberPointCooker->getAddPoint($discountMoney, $memberPointAccount, $currencyUnit, $currency);
                    }
                    //deductPoint if need
                    if ($deductMedias != NULL) {
                        $deductPointMedia = reset($deductMedias);
                        $deductPoint = $deductPointMedia->content;

                        if ($deductPoint == NULL) {
                            //不填写“兑换积分”，则将$deductPoint置为 0
                            $deductPoint = 0;
                        }
                        if (is_numeric($deductPoint) && $deductPoint >= 0) {
                            $memberPointType = $memberPointCooker->getMemberPointTypeByAccount($memberPointAccount);
                            $deductMoney = $memberPointCooker->populateMoneyByMemberPoint($deductPoint, $memberPointType, $currency, $currencyUnit);
                            //deduct money by point
                            $billData['payAmount'] = $billData['amount'] - $deductMoney;
                            //所付的钱 = 消费金额-积分产生的钱-打折的钱
                            //$billData['payAmount'] = $billData['amount'] - $deductMoney
                            $billData['deductedPoint'] = $deductPoint;
                            $billData['deductedMoney'] = $deductMoney;

                            $memberPointCooker->deductMemberPoint($deductPoint, $memberPointAccount);
                            $billData['accountMemberPoint'] = $memberPointAccount->getItem('memberPoint')->getValue();
                            //发送微信消息
                            $options = array(
                                'appid' => 'wxdfdd543f3624de1a',
                                'appsecret' => '0d263ad0ccbd55da5f61b105ffd90ef8'
                            );
                            $wxMobile = '';
                            $wxOpenid = '';
                            $wxName = '';
                            $weObj = new BAWechatCooker($options); //oxmO-uNBCGBjzWouLnH44JrmutiA
                            if (isset($memberData['mobile']) && array_key_exists('mobile', $memberData))
                                $wxMobile = $memberData['mobile'];
                            if (isset($memberData['openid']) && array_key_exists('openid', $memberData))
                                $wxOpenid = $memberData['openid'];
                            if (isset($memberData['name']) && array_key_exists('name', $memberData))
                                $wxName = $memberData['name'];
//                            $wxUser = $weObj->getWXUserByMobile($wxMobile);
//                            $openid = $wxUser['openid'];
//                            $name = $wxUser['name'];
                            //点击微信消息，跳转到“我的消费记录”
                            $sendTemplateMessageControl = new BUIControl('sendTemplateMessage');
                            $myUrl = $sendTemplateMessageControl->getAjaxLinkUrl('showCardUserBillListInMobile', NULL, array(
                                'cooker' => 'BAMemberCard@showCardUserBillList',
                            ));
                            $data = array(
                                'touser' => $wxOpenid,
                                'template_id' => 'Ydu_BAADIxIBbfNRYuHIv1J7P5am-YFz_7WuAreI04g', //kUcnkiodpWpNQcT6tRKbcuFCNyZSIeg-xBpJkDFCQ1g//0sEg7RAxt2Z0q4Y5Qv8WZIMrhYa-mycc8glbtWaGXVQ
                                'url' => 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxdfdd543f3624de1a&redirect_uri=http://hamshun.sinaapp.com/maozhua/2.php&response_type=code&scope=snsapi_base&state=1#wechat_redirect',
                                'topcolor' => '#FF0000',
                                'data' => array(
                                    'first' => array(
                                        'value' => '尊敬的' . $wxName . ', 最新交易提醒：',
                                        'color' => '#000000'
                                    ),
                                    'time' => array(
                                        'value' => date("H") . '时' . date("i") . '分',
                                        'color' => '#000000'
                                    ),
                                    'org' => array(
                                        'value' => '阳光世纪店',
                                        'color' => '#000000'
                                    ),
                                    'type' => array(
                                        'value' => '减少',
                                        'color' => '#000000'
                                    ),
                                    'money' => array(
                                        'value' => $billData['payAmount'],
                                        'color' => '#000000'
                                    ),
                                    'point' => array(
                                        'value' => $addPoint,
                                        'color' => '#000000'
                                    ),
                                    'remark' => array(
                                        'value' => '截止' . date("H") . '时' . date("i") . '分' . '，您的积分卡可用积分为' . $billData['accountMemberPoint'] . '积分。如有疑问请咨询023-86577788',
                                        'color' => '#000000'
                                    ),
                                )
                            );
                            $res = $weObj->sendTemplateMessage($data);
                            if ($res["errcode"] == 0) {
                                //发送消息成功
                            }
                        }
                    }
                }
            }
        }

        if (isset($billData['amount']) && $billData['amount'] != NULL) {
            $totalVoucherMoney = $this->populateBillVoucherMoney();

            if ($totalVoucherMoney != NULL) {
                if (isset($billData['payAmount'])) {
                    $payAmount = $billData['payAmount'];
                    $billData['payAmount'] = $payAmount - $totalVoucherMoney;
                } else {
                    $amount = $billData['amount'];
                    $billData['payAmount'] = $amount - $totalVoucherMoney;
                }

                //更新代金券状态
                $this->usedBillVouchers();
                $billData['deductedVoucherMoney'] = $totalVoucherMoney;
            }
        }

        //final add bill
        $this->addBill($billData + $memberData);

        //test
        //$memberPointCooker = new BAMemberPointCooker();
        //$testAccount = $memberPointCooker->getMemberPointAccountByUser();

        $this->onShowBillList();
    }

    public function onNewMemberBill($data = NULL) {

        $mediaList = $this->postManager->populateMediaListFromPostData($this->postData, 'choose_bill');
        $chooseBillData = array();

        foreach ($mediaList as $media) {
            if ($media->content != NULL) {
                $chooseBillData[$media->name] = $media->content;
            }
        }

        $fixedCardId = NULL;
        $mobile = NULL;
        $account = NULL;
        $memberPointType = NULL;

        if (isset($chooseBillData['fixedCardId'])) {
            $fixedCardId = $chooseBillData['fixedCardId'];
        }
        if (isset($chooseBillData['mobile'])) {
            $mobile = $chooseBillData['mobile'];
        }

        $memberPointCooker = new BAMemberPointCooker();
        if (isset($chooseBillData['memberPointTypeId'])) {
            $memberPointTypeId = $chooseBillData['memberPointTypeId'];
            $memberPointType = $memberPointCooker->getMemberPointType($memberPointTypeId);

            $error = new BAError();
            if ($memberPointType != NULL && $mobile != NULL) {
                $account = $memberPointCooker->getMemberPointAccount(array('mobile' => $mobile), $memberPointType);
                $error->addError('手机号已经被使用！', 'wrongMobile');
            }

            if ($account != NULL) {//means mobile used already
                $this->updateControl->addRenderView('memberPointAccount_exist_error');
            } else {
                $userInfoData = $mobile == NULL ? NULL : array('mobile' => $mobile);
                $accountInfoData = $fixedCardId == NULL ? NULL : array('fixedCardId' => $fixedCardId);
                $memberPointCooker->addMemberPointAccount($memberPointType, $userInfoData, $accountInfoData);
                $this->onShowAddBill();
            }
        }
        //$this->updateControl->addRenderView('not_find_view_error');
    }

    public function onShowManageBill($data = NULL) {
        $this->updateControl->addRenderView('manageBill', 'weCafe_bill_manager');
//        $billType = $this->getCurrentBillType();
//
//        $memberPointCooker = new BAMemberPointCooker();
//        $memberPointTypeList = $memberPointCooker->getMemberPointTypeList('aliasList');
//        if (yii::app()->request->isAjaxRequest) {
//            $this->updateControl->addRenderView('manageBill', 'weCafe_bill_manager', array('memberPointTypeData' => $memberPointTypeList));
//        } else {
//            $control = new BUIEventControl('manageBill');
//            $screen = Blyn::app()->getUIManager()->getCurrentScreen();
//            $screen->addChildControl($control);
//            $control->addRenderView('manageBill', 'weCafe_bill_manager', array('memberPointTypeData' => $memberPointTypeList));
//        }
    }

    public function onShowUserBuyBill() {
        $this->updateControl->addRenderView('showUserBuyBill', 'userBuyBill');
        if (yii::app()->request->isAjaxRequest) {
            $this->updateControl->addRenderView('showUserBuyBill', 'userBuyBill');
        } else {
            $control = new BUIEventControl('manageBill');
            $screen = Blyn::app()->getUIManager()->getCurrentScreen();
            $screen->addChildControl($control);
            $control->addRenderView('showUserBuyBill', 'userBuyBill');
        }
    }

    public function onShowAddBill($data = NULL) {
        //parent::onShowAddBill($data);
        $billId = $this->activeLink->getLinkVariable('billId');
        $billTable = new BASpaceSheet('bill');

        $mediaList = $this->postManager->populateMediaListFromPostData($this->postData, 'choose_bill');
        $chooseBillData = array();

        foreach ($mediaList as $media) {
            if ($media->content != NULL) {
                $chooseBillData[$media->name] = $media->content;
            }
        }

        $model = new BDynamicFormModel();
        $amountField = 'media_amount_add_bill';
        $seatField = 'media_seat_add_bill';
        $billTimeField = 'media_billTime_add_bill';
        $descriptionField = 'media_description_add_bill';

        $fixedCardIdField = 'media_fixedCardId_member_info';
        $mobileField = 'media_mobile_member_info';
        $userNameField = 'media_userName_member_info';
        $openidField = 'media_openid_member_info';
        //$memberPointAccountIdField = 'media_memberPointAccountId_member_info';
        $deductedMemberPointField = 'media_deductedMemberPoint_change_memberPoint';

        $memberPointField = 'media_memberPoint_member_point';

        $model->addField($amountField);
        $model->addField($seatField);
        $model->addField($billTimeField);
        $model->addField($descriptionField);

        //$model->addField($memberPointAccountIdField);
        $model->addField($fixedCardIdField);
        $model->addField($mobileField);
        $model->addField($openidField);
        $model->addField($userNameField);
        $model->addField($deductedMemberPointField);
        $model->addField($memberPointField);

        //populate memberPoint for user
        if ($chooseBillData != NULL) {
            $mobile = isset($chooseBillData['mobile']) ? $chooseBillData['mobile'] : NULL;
            $fixedCardId = isset($chooseBillData['fixedCardId']) ? $chooseBillData['fixedCardId'] : NULL;
            $memberPointCooker = new BAMemberPointCooker();
            if (isset($chooseBillData['memberPointTypeId'])) {
                $memberPointTypeId = $chooseBillData['memberPointTypeId'];
                $memberPointType = $memberPointCooker->getMemberPointType($memberPointTypeId);
                if ($mobile != NULL || $fixedCardId != NULL) {
                    $memberPointAccount = $memberPointCooker->getMemberPointAccount($chooseBillData, $memberPointType);
                    if ($memberPointAccount != NULL) {
                        $memberPointAccountId = $memberPointAccount->getId();

                        if ($memberPointAccount->getItem('userInfoId') != NULL) {
                            $userCooker = new BAUserCooker();
                            $userInfoId = $memberPointAccount->getItem('userInfoId')->getValue();
                            $oUserInfo = $userCooker->getUserInfoById($userInfoId);
                            if ($oUserInfo->getItem('gender')) {
                                $gender = $oUserInfo->getItem('gender')->getValue();
                                $userName = BAUserCooker::getGenderAlias($gender) . '.';
                            }

                            if ($oUserInfo->getItem('familyName')) {
                                $userName.=$oUserInfo->getItem('familyName')->getValue();
                            }
                            if ($oUserInfo->getItem('surName')) {
                                $userName.=$oUserInfo->getItem('surName')->getValue();
                            }
                            if ($oUserInfo->getItem('mobile')) {
                                $userMobile = $oUserInfo->getItem('mobile')->getValue();
                            }
                            if ($oUserInfo->getItem('openid')) {
                                $userOpenid = $oUserInfo->getItem('openid')->getValue();
                            }
                        }

                        if (isset($userName)) {
                            $model->$userNameField = $userName;
                        }

                        $memberPoint = $memberPointAccount->getItem('memberPoint')->getValue();
                        if ($memberPoint == '0') {
                            $memberPoint = '0 ';
                        }
                        $model->$memberPointField = $memberPoint;
                        if (isset($userMobile))
                            $model->$mobileField = $userMobile;
                        if (isset($userOpenid))
                            $model->$openidField = $userOpenid;
                        if ($memberPointAccount->getItem('fixedCardId') != NULL)
                            $model->$fixedCardIdField = $memberPointAccount->getItem('fixedCardId')->getValue();
                    }else {
                        $this->onNewMemberBill();
                        return;
                    }
                }
            }
        }

        if ($billId != NULL && $billId > 0) {

            $bill = $billTable->getListById($billId);

            //将已经存在的活动数据放进MODEL里面
            if ($bill->getItem('fixedCardId') != NULL)
                $model->$fixedCardIdField = $bill->getItem('fixedCardId')->getValue();
            if ($bill->getItem('mobile') != NULL)
                $model->$mobileField = $bill->getItem('mobile')->getValue();
            if ($bill->getItem('deductedMemberPoint') != NULL)
                $model->$deductedMemberPointField = $bill->getItem('deductedMemberPoint')->getValue();
            if ($bill->getItem('amount') != NULL)
                $model->$amountField = $bill->getItem('amount')->getValue();
            if ($bill->getItem('seat') != NULL)
                $model->$seatField = $bill->getItem('seat')->getValue();
            if ($bill->getItem('billTime') != NULL)
                $model->$billTimeField = $bill->getItem('billTime')->getValue();
            if ($bill->getItem('description') != NULL)
                $model->$descriptionField = $bill->getItem('description')->getValue();
        }else { //add a temporary card by userid_spaceid
            $bill = $billTable->getTempList();
        }

        $this->updateControl->addRenderView('billAdd', 'bill_add', array(
            'model' => $model,
            'fixedCardIdField' => $fixedCardIdField,
            'mobileField' => $mobileField,
            'openidField' => $openidField,
            'userNameField' => $userNameField,
            'amountField' => $amountField,
            'memberPointField' => $memberPointField,
            'deductedMemberPointField' => $deductedMemberPointField,
            'seatField' => $seatField,
            'billTimeField' => $billTimeField,
            'descriptionField' => $descriptionField,
            'memberPointAccountId' => isset($memberPointAccountId) ? $memberPointAccountId : 0,
            'bill' => $bill,
            'billId' => $bill->getId()));
    }

    public function initAnalyseTotalChartData($billData = NULL) {
        $todayBegin = strtotime(date('Y-m-d', time()) . ' 00:00:00');
        $todayEnd = $todayBegin + 60 * 60 * 24;
        //初始化10天数据
        $theseDayBill = array();
        for ($i = 9; $i >= 0; $i--) {
            $theseDayBill[$i] = 0;
        }
        $billTime = '';
        $payAmount = '';
        foreach ($billData as $key => $value) {
            $billTime = $value['items']['billTime'];
            $payAmount = $value['totalPayAmount'];
            switch ($billTime) {
                case ($billTime >= $todayBegin && $billTime <= $todayEnd):
                    $theseDayBill[0] += $payAmount;
                    break;
                case ($billTime >= $todayBegin - 60 * 60 * 24 * 1 && $billTime <= $todayEnd - 60 * 60 * 24 * 1):
                    $theseDayBill[1] += $payAmount;
                    break;
                case ($billTime >= $todayBegin - 60 * 60 * 24 * 2 && $billTime <= $todayEnd - 60 * 60 * 24 * 2):
                    $theseDayBill[2] += $payAmount;
                    break;
                case ($billTime >= $todayBegin - 60 * 60 * 24 * 3 && $billTime <= $todayEnd - 60 * 60 * 24 * 3):
                    $theseDayBill[3] += $payAmount;
                    break;
                case ($billTime >= $todayBegin - 60 * 60 * 24 * 4 && $billTime <= $todayEnd - 60 * 60 * 24 * 4):
                    $theseDayBill[4] += $payAmount;
                    break;
                case ($billTime >= $todayBegin - 60 * 60 * 24 * 5 && $billTime <= $todayEnd - 60 * 60 * 24 * 5):
                    $theseDayBill[5] += $payAmount;
                    break;
                case ($billTime >= $todayBegin - 60 * 60 * 24 * 6 && $billTime <= $todayEnd - 60 * 60 * 24 * 6):
                    $theseDayBill[6] += $payAmount;
                    break;
                case ($billTime >= $todayBegin - 60 * 60 * 24 * 7 && $billTime <= $todayEnd - 60 * 60 * 24 * 7):
                    $theseDayBill[7] += $payAmount;
                    break;
                case ($billTime >= $todayBegin - 60 * 60 * 24 * 8 && $billTime <= $todayEnd - 60 * 60 * 24 * 8):
                    $theseDayBill[8] += $payAmount;
                    break;
                case ($billTime >= $todayBegin - 60 * 60 * 24 * 9 && $billTime <= $todayEnd - 60 * 60 * 24 * 9):
                    $theseDayBill[9] += $payAmount;
                    break;
                default :
                    break;
            }
        }
        return $theseDayBill;
    }

    public function initAnalyseIntervaFrequencylChartData() {
        
    }

    public function onShowBillAnalyse() {

        //test getBillIntervalData
        $intervalData = $this->getBillIntervaFrequencylData(array('timeSlotUnit' => 'day', 'timeSlotCount' => 30));
//        $intervalData = array(2 => 1, 5 => 10, 10 => 60, 15 => 40, 20 => 12);
        $billData = $this->getTobalBillByPeriod(array('timeSlotUnit' => 'day', 'timeSlotCount' => 10));
        $oAnalyseTotalBill = $this->initAnalyseTotalChartData($billData);
//        $oAnalyseIntervaFrequencyl = $this->initAnalyseIntervaFrequencylChartData();
        $analyseTotalData = array(
            'chartTitle' => '最近10天营业总金额趋势图 ',
            'Y_axis' => '金额',
            'X_axis' => '日期',
            'chartData' => $oAnalyseTotalBill
        );
        $analyseIntervaFrequencyl = array(
            'chartTitle' => '最近1个月间隔消费趋势图 ',
            'Y_axis' => '消费次数',
            'X_axis' => '间隔天数',
            'chartData' => $intervalData, //$intervalData
        );
        $this->updateControl->addRenderView('billAnalyse', 'bill_analyse', array(
            'analyseTotalData' => $analyseTotalData,
            'analyseIntervaFrequencyl' => $analyseIntervaFrequencyl,
        ));
    }

    public function onShowBillAnalyseTotalBill($control = NULL) {

        $postData = $this->postManager->populatePostDataByIndex($this->postData, 'analyse_total_bill');

        $analyseTotalData = array(
            'chartTitle' => '营业总金额趋势图 ',
            'Y_axis' => '金额',
            'X_axis' => '日期',
            'chartPeriodData' => array(),
            'chartValueData' => array()
        );

        $timeSlotUnit = NULL;
        $timeSlotLength = NULL;
        $timeSlotCount = NULL;
        $endTime = NULL;

        $timeData = array();

        //默认显示10天的数据
        $timeData['timeSlotUnit'] = 'day';
        $timeData['timeSlotCount'] = 10;
        $timeData['endTime'] = 'now';

        if ($postData != NULL) {
            $timeData = $timeData + $postData;
        }

        $period = $this->activeLink->getLinkVariable('period');
        if ($period != NULL) {
            if ($period == '10days') {
                $timeData['timeSlotUnit'] = 'day';
                $timeData['timeSlotCount'] = 10;
            }
            if ($period == '20days') {
                $timeData['timeSlotUnit'] = 'day';
                $timeData['timeSlotCount'] = 20;
            }
            if ($period == '6weeks') {
                $timeData['timeSlotUnit'] = 'week';
                $timeData['timeSlotCount'] = 6;
            }
            if ($period == '6months') {
                $timeData['timeSlotUnit'] = 'month';
                $timeData['timeSlotCount'] = 6;
            }
        }

        //$billData = $this->getTobalBillByPeriod(array('timeSlotUnit' => 'day', 'timeSlotCount' => 10));
        $billDataCollection = $this->getTobalBillByPeriod($timeData);

        //$billItems = $billData['items'];

        $timerCooker = new BATimerCooker();
        $periodData = $timerCooker->populateTimePeriod($timeData);
        $startTime = $periodData['startTime'];
        $endTime = $periodData['endTime'];
        $timeSlot = $periodData['timeSlot'];
        $timeSlotUnit = $timeData['timeSlotUnit'];
        $timeSlotCount = $timeData['timeSlotCount'];

        $timeSlotEndTime = $startTime + $timeSlot;

        $chartPeriodData = array();
        $chartValueData = array();
        $billTime = NULL;
        while ($timeSlotEndTime <= $endTime) {

            if ($timeSlotUnit == 'day') {
                $analyseTotalData['chartTitle'] = '最近' . $timeSlotCount . '天营业额趋势图';
                $analyseTotalData['X_axis'] = '日期';
                array_push($chartPeriodData, date('m-d', $timeSlotEndTime));
                $billTime = date('Ymd', $timeSlotEndTime);
            }
            if ($timeSlotUnit == 'week') {
                $analyseTotalData['chartTitle'] = '最近' . $timeSlotCount . '星期营业额趋势图';
                $analyseTotalData['X_axis'] = '星期';
                array_push($chartPeriodData, date('Y-W', $timeSlotEndTime));
                $billTime = date('Y-W', $timeSlotEndTime);
            }
            if ($timeSlotUnit == 'month') {
                $analyseTotalData['chartTitle'] = '最近' . $timeSlotCount . '月营业额趋势图';
                $analyseTotalData['X_axis'] = '月份';
                array_push($chartPeriodData, date('Y-m', $timeSlotEndTime));
                $billTime = date('Ym', $timeSlotEndTime);
            }
            if ($timeSlotUnit == 'year') {
                $analyseTotalData['chartTitle'] = '最近' . $timeSlotCount . '年营业额趋势图';
                $analyseTotalData['X_axis'] = '年份';
                array_push($chartPeriodData, date('Y', $timeSlotEndTime));
                $billTime = date('Y', $timeSlotEndTime);
            }

            $chartValueData[$billTime] = 0;

            $timeSlotEndTime+=$timeSlot;
        }

        foreach ($billDataCollection as $billData) {
            $billItems = $billData['items'];
            if ($timeSlotUnit == 'day') {
                $billTime = $billItems['billDate'];
                $chartValueData[$billTime] = $billData['totalPayAmount'];
            }
            if ($timeSlotUnit == 'week') {
                $billTime = $billItems['billWeek'];
                $chartValueData[$billTime] = $billData['totalPayAmount'];
            }
            if ($timeSlotUnit == 'month') {
                $billTime = $billItems['billMonth'];
                $chartValueData[$billTime] = $billData['totalPayAmount'];
            }
            if ($timeSlotUnit == 'year') {
                $billTime = $billItems['billYear'];
                $chartValueData[$billTime] = $billData['totalPayAmount'];
            }
        }
        $analyseTotalData['chartPeriodData'] = $chartPeriodData;
        $analyseTotalData['chartValueData'] = $chartValueData;

        if ($control instanceof BUIControl) {
            $control->addRenderView('billAnalyseTotal', 'bill_analyse_totalBill', array(
                'analyseTotalData' => $analyseTotalData,
            ));
            $control->render();
        }

        $this->updateControl->addRenderView('billAnalyseTotal', 'bill_analyse_totalBill', array(
            'analyseTotalData' => $analyseTotalData,
        ));
    }

    public function onShowBillAnalyseIntervalFrequency($control = NULL) {
        $postData = $this->postManager->populatePostDataByIndex($this->postData, 'analyse_interval_frequency');

        $maxCount = NULL;
        $minCount = NULL;
        if (isset($postData['countOption']) && $postData['countOption'] != 0) {
            if ($postData['operator'] == '>') {
                $minCount = $postData['countOption'];
            }
            if ($postData['operator'] == '<') {
                $maxCount = $postData['countOption'];
            }
        }

        $analyseData = array(
            'chartTitle' => '回访时间间隔趋势图 ',
            'y_axis' => '发生次数',
            'x_axis' => '回访时间间隔',
            'xData' => array(),
            'yData' => array()
        );

        //默认显示10天的数据
        $timeData['timeSlotUnit'] = 'day';
        $timeData['timeSlotCount'] = 10;
        $timeData['endTime'] = 'now';

        if ($postData != NULL) {
            $timeData = $timeData + $postData;
        }

        $period = $this->activeLink->getLinkVariable('period');
        if ($period != NULL) {
            if ($period == '24hours') {
                $timeData['timeSlotUnit'] = 'hour';
                $timeData['timeSlotCount'] = 24;
            }
            if ($period == '10days') {
                $timeData['timeSlotUnit'] = 'day';
                $timeData['timeSlotCount'] = 10;
            }
            if ($period == '20days') {
                $timeData['timeSlotUnit'] = 'day';
                $timeData['timeSlotCount'] = 20;
            }
            if ($period == '6weeks') {
                $timeData['timeSlotUnit'] = 'week';
                $timeData['timeSlotCount'] = 6;
            }
            if ($period == '6months') {
                $timeData['timeSlotUnit'] = 'month';
                $timeData['timeSlotCount'] = 6;
            }
        }

        $timeSlotUnit = $timeData['timeSlotUnit'];
        $timeSlotCount = $timeData['timeSlotCount'];
        if ($timeSlotUnit == 'hour') {
            $analyseData['chartTitle'] = '最近' . $timeSlotCount . '小时统计';
            //$analyseTotalData['x_axis'] = '间隔小时';
        }
        if ($timeSlotUnit == 'day') {
            $analyseData['chartTitle'] = '最近' . $timeSlotCount . '天统计';
            //$analyseTotalData['x_axis'] = '间隔天数';
        }
        if ($timeSlotUnit == 'week') {
            $analyseData['chartTitle'] = '最近' . $timeSlotCount . '个星期统计';
            //$analyseTotalData['x_axis'] = '间隔星期';
        }
        if ($timeSlotUnit == 'month') {
            $analyseData['chartTitle'] = '最近' . $timeSlotCount . '个月统计';
            //$analyseTotalData['x_axis'] = '间隔星期';
        }

        $intervalDataCollection = $this->getBillIntervaFrequencylData($timeData);
        //asort($intervalDataCollection);

        $xData = array();
        $yData = array();
        $countOptions = array();
        foreach ($intervalDataCollection as $interval => $frequency) {
            if ($maxCount != NULL && $frequency < $maxCount) {
                array_push($xData, $interval . $timeSlotUnit);
                array_push($yData, $frequency);
            } elseif ($minCount != NULL && $frequency > $minCount) {
                array_push($xData, $interval . $timeSlotUnit);
                array_push($yData, $frequency);
            } else {
                array_push($xData, $interval . $timeSlotUnit);
                array_push($yData, $frequency);
            }

            $countOptions[$frequency] = $frequency;
        }

        $analyseData['xData'] = $xData;
        $analyseData['yData'] = $yData;
        $analyseData['countOptions'] = $countOptions;

        if ($control instanceof BUIControl) {
            $control->addRenderView('analyseIntervalFrequency', 'bill_analyse_intervalFrequency', array(
                'analyseData' => $analyseData,
            ));
            $control->render();
        }


        $this->updateControl->addRenderView('analyseIntervalFrequency', 'bill_analyse_intervalFrequency', array(
            'analyseData' => $analyseData,
        ));
    }

}
